/**
 * 日志导出服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, Logger } from '@nestjs/common';
import { LogService } from './log.service';
import { ILogQuery } from '../../interfaces/log.interface';
import * as ExcelJS from 'exceljs';
import { Response } from 'express';

@Injectable()
export class LogExportService {
  private readonly logger = new Logger(LogExportService.name);

  constructor(private readonly logService: LogService) {}

  /**
   * 导出日志到Excel
   * @param query 查询条件
   * @param response Express响应对象
   */
  async exportToExcel(query: ILogQuery, response: Response): Promise<void> {
    try {
      // 查询日志数据
      const [logs] = await this.logService.findAll(query);

      // 创建工作簿和工作表
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('系统日志');

      // 设置表头
      worksheet.columns = [
        { header: '日志ID', key: 'id', width: 10 },
        { header: '日志类型', key: 'type', width: 15 },
        { header: '日志级别', key: 'level', width: 15 },
        { header: '操作用户', key: 'username', width: 20 },
        { header: '操作IP', key: 'ip', width: 15 },
        { header: '请求方法', key: 'method', width: 10 },
        { header: '请求路径', key: 'path', width: 30 },
        { header: '操作结果', key: 'result', width: 30 },
        { header: '错误信息', key: 'error', width: 30 },
        { header: '执行时长(ms)', key: 'duration', width: 15 },
        { header: '创建时间', key: 'created_at', width: 20 },
      ];

      // 添加数据
      worksheet.addRows(logs);

      // 设置响应头
      response.setHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      );
      response.setHeader(
        'Content-Disposition',
        'attachment; filename=system_logs.xlsx',
      );

      // 写入响应流
      await workbook.xlsx.write(response);
      response.end();
    } catch (error) {
      this.logger.error('Failed to export logs:', error);
      throw error;
    }
  }
} 